using System.Data;
using System.Data.SqlClient;
using ServiceStack.OrmLite;
using STHPMS1.DAL.D_Core;
using STHPMS1.ICore.I_DAL;
using STHPMS1.Common.C_Extension;
using STHPMS1.ICore.I_DAL.Repository;

namespace STHPMS1.DAL.D_Repository
{
	public class DataTableRepository : DalBase, IDataTableRepository
	{
        public DataTable FillDataTable(string sql)
        {
            DataTable table = new DataTable();
            using (SqlConnection sqlCon = new SqlConnection(Adapter.ConnectionString))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(sql, sqlCon))
                {
                    da.Fill(table);
                }
            }
            return table;
        }

		public DataTable GetDataTable (string tablename)
		{
			string sql = string.Format ("select * from {0}", tablename);
			DataTable table = new DataTable ();
            using (SqlConnection sqlCon = new SqlConnection(Adapter.ConnectionString))
            {
				using (SqlDataAdapter da = new SqlDataAdapter (sql, sqlCon)) {
					da.Fill (table);
					da.FillSchema (table, SchemaType.Source);
				}
			}
			return table;
		}

		public int SaveDataTable (DataTable tb)
		{
			int val = 0;
			string sql = string.Format ("select * from {0}", tb.TableName);
            using (SqlConnection sqlCon = new SqlConnection(Adapter.ConnectionString))
            {
				using (SqlDataAdapter da = new SqlDataAdapter (sql, sqlCon)) {
					SqlCommandBuilder builder = new SqlCommandBuilder (da);
					val = da.Update (tb);
				}
			}
			return val;
		}

		public void DropTable<T> ()
		{
            using (IDbConnection conn = Adapter.OpenDbConnection())
            {
				conn.DropTable<T> ();
			}
		}
	}
}
